package Translation;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpTranslateClient {
    private DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;

    public UdpTranslateClient (String serverIp,int serverPort) throws SocketException {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
        socket = new DatagramSocket();
    }

    public void start() throws IOException {
        while (true) {
            System.out.print("->");
            Scanner sc = new Scanner(System.in);
            // 1. 根据用户的输入 构造请求
            String request = sc.next();
            if(request.equals("exit")){
                System.out.println("exit!");
                return;
            }
            // 2. 发送请求给服务器
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                                                    InetAddress.getByName(serverIp),serverPort);
            socket.send(requestPacket);
            // 3. 读取服务器的响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(),0, responsePacket.getLength());
            System.out.println(response);
            // 4. 解析响应并显式
            String log = String.format("req: %s; resp: %s",request,response);
            System.out.println(log);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpTranslateClient client = new UdpTranslateClient("127.0.0.1",9090);
        client.start();
    }
}
